package com.wego.controller;

import com.wego.bean.StateBean;
import com.wego.bean.TableBean;
import com.wego.common.bean.PageBean;
import com.wego.entity.domain.Announcement;
import com.wego.entity.domain.Carousel;
import com.wego.entity.query.AnnouncementQuery;
import com.wego.ex.GlobalException;
import com.wego.service.AnnouncementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.util.List;

@Controller
@RequestMapping("manager/announcement")
public class AnnouncementController {

    @Autowired
    private AnnouncementService announcementService;

    @GetMapping("/list")
    public @ResponseBody TableBean list(AnnouncementQuery announcementQuery) {
        //构造动态查询条件
        PageBean<Announcement> announcementPageBean = announcementService.selectPage(announcementQuery);
        List<Announcement> announcements = announcementPageBean.getResult();
        Long count = announcementPageBean.getTotal();
        TableBean tableBean = new TableBean<Announcement>();
        tableBean.setCode(0);
        tableBean.setMsg("");
        tableBean.setData(announcements);
        tableBean.setCount(count);
        return tableBean;
    }

    @GetMapping("/openAddUpdate")
    public String openAddUpdate(Long id, Model model) {
        if (id != null) {
            Announcement announcement = announcementService.selectByPrimaryKey(id);
            model.addAttribute("announcement", announcement);
        }
        return "manager/announcement_add_update";
    }

    @PostMapping("/updateState")
    public @ResponseBody StateBean updateState(Long id, Model model) {
        Announcement announcement = announcementService.selectByPrimaryKey(id);
        Integer state = announcement.getState();
        if (state == null && id == null) {
            throw new GlobalException(400, "执行修改状态时提交的参数不正确", "list");
        }
        //修改状态的值
        announcement.setState(state == 1 ? 0 : 1);
        announcement.setUpdateTime(LocalDateTime.now());
        announcementService.updateByPrimaryKeySelective(announcement);
        return new StateBean(200, "更新成功");
    }

}
